﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Super.Common;

namespace Super.DomainService
{
    /// <summary>
    /// 实体分页通用类。
    /// </summary>
    /// <typeparam name="TEntity">实体类型。</typeparam>
    public class PagedEntities<TEntity>
    {
        private readonly IEnumerable<TEntity> _itemCollection;
        private readonly int _itemCount;
        private readonly int _pageIndex;
        private readonly int _pageSize;

        /// <summary>
        /// 构造函数。
        /// </summary>
        /// <param name="pageIndex">当前页码。</param>
        /// <param name="pageSize">分页大小。</param>
        /// <param name="itemCollection">实体集合。</param>
        /// <param name="itemCount">实体总数。</param>
        public PagedEntities(int pageIndex, int pageSize, IEnumerable<TEntity> itemCollection, int itemCount)
        {
            _pageIndex = pageIndex;
            _pageSize = pageSize;
            _itemCollection = itemCollection;
            _itemCount = itemCount;
        }


        /// <summary>
        /// 当前页码。
        /// </summary>
        public int PageIndex
        {
            get { return _pageIndex; }
        }

        /// <summary>
        /// 分页大小。
        /// </summary>
        public int PageSize
        {
            get { return _pageSize; }
        }

        /// <summary>
        /// 实体集合。
        /// </summary>
        public IEnumerable<TEntity> ItemCollection
        {
            get { return _itemCollection; }
        }

        /// <summary>
        /// 实体总数。
        /// </summary>
        public int ItemCount
        {
            get { return _itemCount; }
        }

        /// <summary> 分页之前的 Queryable.
        /// </summary>
        public IQueryable<TEntity> SourceQueryable { get; set; }

        /// <summary> 转换PageInfo对象.
        /// </summary>
        /// <returns></returns>
        public PageInfo ToPageInfo()
        {
            return new PageInfo { PageNum = PageIndex, PageSize = PageSize, ItemCount = ItemCount };
        }

        /// <summary> 附加分页信息
        /// </summary>
        /// <param name="key">所需页数的参数名 同一Controller 中不可重复</param> 
        public void AttachPageInfo(string key = "page")
        {
            var pi = new PageInfo { Key = key, PageNum = PageIndex, PageSize = PageSize, ItemCount = ItemCount, ItemCollection = ItemCollection };

            Common.DataCache.NowController.ViewData[key] = pi;
        }
    }
}